package main

import (
	"chat-client-demo/command"
	"log"
	"strconv"
	"time"

	"google.golang.org/protobuf/proto"
)

func init() {
	cmder.Add(&command.Command{
		Name: "login",
		Args: func(a *command.Args) {
			a.Register("user_id")
		},
		Run: func(a command.ArgMap) {
			id := a.Int64("user_id")
			if id == 0 {
				log.Printf("no user id")
				return
			}
			loginReq(id)
		},
	})

	cmder.Add(&command.Command{
		Name: "msg",
		Args: func(a *command.Args) {
			a.Register("user_id")
			a.Register("content")
		},
		Run: func(a command.ArgMap) {
			id := a.Int64("user_id")
			if id == 0 {
				log.Printf("no user id")
				return
			}

			content := a.String("content")
			if len(content) == 0 {
				log.Printf("no content")
				return
			}
			msgReq(id, content)
		},
	})
}

// 登录处理
func loginReq(id int64) {
	loginMsg := &Message{
		From:       id, // 此时应该不知道userId
		To:         ServerId,
		Cmd:        CommandType_LOGIN_REQ,
		CreateTime: time.Now().UnixNano() / 1e6,
		MsgType:    MsgType_TEXT,
		ChatType:   ChatType_PRIVATE,
		Content:    strconv.FormatInt(id, 10),
	}
	loginMsgData, _ := proto.Marshal(loginMsg)
	pbData, err := Encode(loginMsgData)
	if err != nil {
		panic(err)
	}
	_, _ = conn.Write(pbData)
}

// 聊天处理
func msgReq(to int64, content string) {
	chatMsg := &Message{
		From:       userId,
		To:         to,
		Cmd:        CommandType_MSG_REQ,
		CreateTime: time.Now().UnixNano() / 1e6,
		MsgType:    MsgType_TEXT,
		ChatType:   ChatType_PRIVATE,
		Content:    content,
	}
	loginMsgData, _ := proto.Marshal(chatMsg)
	pbData, err := Encode(loginMsgData)
	if err != nil {
		panic(err)
	}
	_, _ = conn.Write(pbData)
}
